<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !assetDetailInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-del>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
          <template v-slot:filter-uploadExcel>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
      </div>

      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetCode="scope">
          <span
            v-if="scope.row.assetCode"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.assetCode }}</span
          >
          <span v-else>-</span>
        </template>
      </TableContainer>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 明细信息 -->
    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <AssetCardDetail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="assetAnalysis">
import { getAssetAnalysisPage, deleteAssetAnalysis } from '@/api/asset'
import Modify from './modify'
import detail from './detail'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { exportTemplateExcel } from '@/api/pub.js'
import { getSupplierAll, getDeptAll, getDepotAll } from '@/api/core'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance()
const uploadInfo = ref({
  action: axios.defaults.baseURL + '/asset/analy/assetAnalysis/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})

// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    // deptAuth: 'id',
    // supplierAuth: 'supplierId',
    // depotAuth: 'id',
  },
  list: [
    {
      componentType: 'input',
      label: '资产卡片号',
      value: 'assetCodeLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '资产名称',
      value: 'assetNameLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '厂家名称',
      value: 'brandNameLike',
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierIdMult',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: { sort: 'create_time desc' },
      clearable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      multiple: true,
      event: search,
    },
    {
      label: '仓库',
      value: 'depotIdMult',
      query: {
        status: 1,
      },
      api: getDepotAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '使用部门',
      value: 'useDeptIdMult',
      query: {
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      label: '管理部门',
      value: 'manageDeptIdMult',
      query: {
        // deptAuth: 'id',
        status: 1,
      },
      api: getDeptAll,
      componentType: 'slip-select',
      multiple: true,
      event: search,
    },
    {
      componentType: 'input',
      label: '位置',
      value: 'locationLike',
      event: search,
    },
  ],
  btn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetAnalysis:add'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('assetAnalysis:del'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('assetAnalysis:downloadTemplate'),
    },
    {
      type: 'slot',
      label: '导入',
      value: 'uploadExcel',
      show: proxy.$permission('assetAnalysis:import'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getAssetAnalysisPage,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产名称',
      value: 'assetName',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'slot',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    { label: '仓库', value: 'depotName' },
    { label: '使用部门', value: 'useDeptName' },
    { label: '管理部门', value: 'manageDeptName' },
    { label: '位置', value: 'location' },
    { label: '设备购入金额(元)', value: 'primitiveOriginalAmount' },
    { label: '预计检查(治疗)人次/月', value: 'estimateTreatPersonTime' },
    { label: '预计检查(治疗)收入/月', value: 'estimateTreatIncome' },
    { label: '预计开机时长/月', value: 'estimatePowerUp' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetAnalysis:update'),
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetAnalysis:del'),
      },
      {
        label: '效益详情',
        event: toDetails,
        show: proxy.$permission('assetAnalysis:benefitsDetail'),
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'assetAnalysis' && el.url === val.url) {
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.value.visible = true
                  let data = {
                    id: val.businessId,
                  }
                  detailInfo.value.tableRow = data
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
const canDelete = computed(() => {
  return tableInfo.value.selections.length
})
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function downloadTemplate() {
  exportTemplateExcel('asset_analysis_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function returnModify() {
  getList()
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
//创建
function create() {
  modifyInfo.value.title = '新增效益分析资产'
  modifyInfo.value.visible = true
  modifyInfo.value.orderId = null
}
//更新
function update(row) {
  modifyInfo.value.title = '修改效益分析资产'
  modifyInfo.value.orderId = row.id
  modifyInfo.value.visible = true
}
//跳转资产卡片详情
function showDetail(row) {
  if (row.assetId && row.assetId !== -2) {
    assetDetailInfo.value.id = row.assetId
    assetDetailInfo.value.visible = true
  }
}
function toDetails(row) {
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}

//删除
function del(row = undefined) {
  const ids = _getIds(row)
  deleteAssetAnalysis(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
onMounted(() => {
  getList()
})
</script>

<style scoped></style>
